package com.itheima.health.service.impl;


import com.itheima.health.common.RedisConst;
import com.itheima.health.common.RedisMessageConstant;
import com.itheima.health.dao.MemberDao;
import com.itheima.health.dto.SmsLoginParam;
import com.itheima.health.service.SendSmsService;
import com.itheima.health.util.AliSmsUtil;
import com.itheima.health.util.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;


@Service
public class SendSmsServiceImpl implements SendSmsService {
    public static long EXPIRE_TIME=300*1000;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RandomUtils randomUtils;

    @Autowired
    private MemberDao memberDao;

    @Override
    public Boolean sendMessage(String type, String telephone) {
        AliSmsUtil aliSmsUtil = new AliSmsUtil();
        String code = null;
        if (type.equals("MOBILE_SIGNIN")) {
            code = validateCodeLogin(type,telephone);
        } else if (type.equals("ORDER")) {
            code = validateCodeOrderSetting(type,telephone);
        }
        return aliSmsUtil.sendMess(telephone, code);

    }

    //预约验证码
    private String validateCodeLogin(String type, String telephone) {
        String code = randomUtils.getRandomNumber();
        Map map = new HashMap();
        map.put("type",type);
        map.put("telephone",telephone);
        map.put(RedisConst.VALIDATE_CODE_PREFIX,code);
        //把数据添加进redis
        redisTemplate.opsForValue().set(telephone + RedisMessageConstant.SENDTYPE_LOGIN,map);
        //设置过期时间
        Duration duration= Duration.ofMillis(EXPIRE_TIME);
        //设置定时删除
        redisTemplate.expire(telephone + RedisMessageConstant.SENDTYPE_LOGIN,duration);

        return code;
    }

    //登录验证码
    private String validateCodeOrderSetting(String type, String telephone) {
        String code = randomUtils.getRandomNumber();
        Map map = new HashMap();
        map.put("type",type);
        map.put("telephone",telephone);
        map.put(RedisConst.VALIDATE_CODE_PREFIX,code);
        //把数据添加进redis
        redisTemplate.opsForValue().set(telephone + RedisMessageConstant.SENDTYPE_ORDER,map);
        //设置过期时间
        Duration duration= Duration.ofMillis(EXPIRE_TIME);
        //设置定时删除
        redisTemplate.expire(telephone + RedisMessageConstant.SENDTYPE_ORDER,duration);

        return code;
    }

    @Override
    public Boolean findByKey(SmsLoginParam smsLoginParam) {
        Map map = (Map) redisTemplate.opsForValue().get(smsLoginParam.getTelephone() + RedisMessageConstant.SENDTYPE_LOGIN);
        String code = (String) map.get(RedisConst.VALIDATE_CODE_PREFIX);
        if(code.equals(smsLoginParam.getValidateCode())){
            return true;
        }
        return false;
    }
}
